import {
  AUTH_SUCCESS,
  ERROR_MSG,
  RECEIVE_USER,
  REST_USER,
  RECEIVE_ICON,
  RECEIVE_USER_LIST
} from './action-type'
import {
  reqRegister,
  reqLogin,
  reqUpdateUser,
  headerIcon,
  reqUser,
  reqUserList
} from './../api/index'

import Cookies from 'js-cookie'

const errorMsg = msg => ({
  type: ERROR_MSG,
  data: msg
})

const authSuccess = msg => ({
  type: AUTH_SUCCESS,
  data: msg
})

const receiveUser = user => ({
  type: RECEIVE_USER,
  data: user
})
const restUser = msg => ({
  type: REST_USER,
  data: msg
})

const receiveIcon = iconLsit => ({
  type: RECEIVE_ICON,
  data: iconLsit
})
const receiveUserList = users => ({
  type: RECEIVE_USER_LIST,
  data: users
})
export function register({ username, password, password2, type }) {
  if (!username || !password || !type) {
    return errorMsg('用户名密码必须输入')
  }
  if (password !== password2) {
    return errorMsg('密码和确认密码不同')
  }
  return async dispatch => {
    const response = await reqRegister({ username, password, type })
    const result = response.data
    if (result.code === 0) {
      dispatch(authSuccess(result.data))
    } else {
      dispatch(ERROR_MSG(result.data))
    }
  }
}

export const login = ({ username, password }) => {
  if (!username || !password) {
    return errorMsg('用户密码必须输入')
  }
  return async dispatch => {
    const response = await reqLogin({ username, password })
    const result = response.data
    if (result.code === 0) {
      Cookies.set('user', result.data)
      Cookies.set('userid', result.data.id)
      dispatch(authSuccess(result.data))
    } else {
      dispatch(ERROR_MSG(result.data))
    }
  }
}

export const updateUser = user => {
  return async dispatch => {
    const response = await reqUpdateUser(user)
    const result = response.data
    if (result.code === 0) {
      Cookies.set('user', result.data)
      Cookies.set('userid', result.data.id)
      dispatch(receiveUser(result.data))
    } else {
      dispatch(restUser(result.data))
    }
  }
}

export const receiveHeader = () => {
  return async dispatch => {
    const response = await headerIcon()
    const result = response.data
    dispatch(receiveIcon(result))
  }
}

export const getUser = () => {
  return async dispatch => {
    const res = await reqUser()
    const result = res.data
    if (result.code === 0) {
      dispatch(receiveUser(result.data))
    } else {
      dispatch(restUser(result.data))
    }
  }
}

export const getUserList = () => {
  return async dispatch => {
    const res = await reqUserList()
    const result = res.data
    if (result.code === 0) {
      dispatch(receiveUserList(result.data))
    }
  }
}
